<template>
  <div class="address-input-wrapper flex-row">
    <div class="address-input-item-wrapper">
      <ElCascader
        v-model="internalVal.address"
        :options="options"
        :disabled="inputDisabled"
        :props="{ label: 'name', value: labelAsValue ? 'name' : 'id' }" />
    </div>
    <div class="address-input-item-wrapper flex-item">
      <ElInput v-model="internalVal.detailAddress" placeholder="请输入详细地址！" :disabled="inputDisabled" />
    </div>
  </div>
</template>

<script>
  export default {
    name: 'AddressInput',
    inject: {
      elForm: {
        default: ''
      },
      elFormItem: {
        default: ''
      }
    },
    props: {
      options: {
        type: Array,
        default() {
          return []
        }
      },
      value: {
        type: Object,
        default: () => ({})
      },
      labelAsValue: Boolean,
      disabled: Boolean
    },
    data() {
      return {
        internalVal: {
          address: [],
          detailAddress: ''
        }
      }
    },
    computed: {
      inputDisabled() {
        return this.disabled || (this.elForm || {}).disabled
      }
    },
    watch: {
      value: {
        immediate: true,
        deep: true,
        handler(newVal) {
          if (newVal) {
            this.internalVal.address = newVal.address
            this.internalVal.detailAddress = newVal.detailAddress
          }
        }
      },
      internalVal: {
        immediate: true,
        deep: true,
        handler(newVal) {
          if (!newVal.address && !newVal.detailAddress) {
            this.$emit('input', undefined)
          } else {
            this.$emit('input', newVal)
          }
        }
      }
    }
  }
</script>

<style lang="scss">
  .address-input-wrapper {
    width: 100%;
  }

  .address-input-item-wrapper {
    padding-right: 5px;

    .el-cascader,
    .el-input {
      width: 100%;
    }
  }
</style>
